import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bike_ride/api/common_repository.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/util/permission_utils.dart';
import 'package:bike_ride/common/widget/dialog/mydialog.dart';
import 'package:bike_ride/common/widget/gallery/gallery_photo_view_page.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image_picker/image_picker.dart';

GlobalKey<PickImgGalleryState> pickImgGlalleryKey = GlobalKey();

class PickImgGallery extends StatefulWidget {
  final List<String> initList;
  final ValueChanged<List<String>>? onChange;
  final bool isOnlyPreview;
  final int maxCount;
  final Color buttonColor;
  final double? width;
  //点击添加图片item回调，方便外部存在TextFormField组件回收焦点
  final Function? onTap;

  const PickImgGallery({
    Key? key,
    required this.initList,
    this.onChange,
    this.isOnlyPreview = false,
    this.maxCount = -1,
    this.buttonColor = const Color(0xffDEDEDE),
    this.width,
    this.onTap,
  }) : super(key: key);
  @override
  State<PickImgGallery> createState() => PickImgGalleryState();
}

class PickImgGalleryState extends State<PickImgGallery> {
  final ImagePicker _imgPicker = ImagePicker();
  List<String> _imgUrls = [];

  @override
  void initState() {
    super.initState();
    _imgUrls = widget.initList;
  }

  void initImgList(List<String> list) {
    setState(() {
      _imgUrls = list;
    });
  }

  @override
  void didUpdateWidget(PickImgGallery oldWidget) {
    _imgUrls = widget.initList;
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return _buildGridViewList();
  }

  // 底部弹出菜单actionSheet
  Widget actionSheet(BuildContext context) {
    return CupertinoActionSheet(
      actions: <Widget>[
        CupertinoActionSheetAction(
          child: Text(
            '打开相机拍照',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w500,
              height: 1.3,
              color: Theme.of(context).colorScheme.primary,
            ),
          ),
          onPressed: () async {
            PermissionUtil.handleCameraPermission(context,(bool success,String msg){
              if(success){
                // 关闭菜单
                if (mounted) {
                  Navigator.of(context).pop();
                }
                // 打开相机拍照
                _getCameraImage();
              }else{
                EasyLoading.showError(msg);
              }
            });
          },
        ),
        CupertinoActionSheetAction(
          child: Text(
            '打开相册，选取照片',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w500,
              height: 1.3,
              color: Theme.of(context).colorScheme.primary,
            ),
          ),
          onPressed: () {
            // 打开相册，选取照片
            _getGalleryImage();
            // 关闭菜单
            Navigator.of(context).pop();
          },
        )
      ],
      cancelButton: CupertinoActionSheetAction(
        child: Text(
          '取消',
          style: TextStyle(
            fontSize: 36.rpx,
            fontWeight: FontWeight.w500,
            color: Theme.of(context).colorScheme.primary,
          ),
        ),
        onPressed: () {
          // 关闭菜单
          Navigator.of(context).pop();
        },
      ),
    );
  }


  Future _getCameraImage() async {
    var image = await _imgPicker.pickImage(source: ImageSource.camera); // 使用相机
    _uploadPic(image);
  }

  Future _getGalleryImage() async {
    var image = await _imgPicker.pickImage(source: ImageSource.gallery); // 使用图库
    _uploadPic(image);
  }

  // 上传图片
  void _uploadPic(Object? imgfile) async {
    if (imgfile == null) {
      return;
    }
    int fileLength;
    Uint8List bytes;
    if(imgfile is XFile){
      fileLength = await imgfile.length();
      bytes = await imgfile.readAsBytes();
    }else if(imgfile is File){
      fileLength = await imgfile.length();
      bytes = await imgfile.readAsBytes();
    }else{
      return;
    }

    int quality = 95;
    if (fileLength > 5 * 1024 * 1024) {
      quality = 83;
    } else if (fileLength > 4 * 1024 * 1024) {
      quality = 86;
    } else if (fileLength > 3 * 1024 * 1024) {
      quality = 89;
    } else if (fileLength > 2 * 1024 * 1024) {
      quality = 92;
    }

    EasyLoading.show(status: '图片上传中');

    Uint8List compressBytes =
        await FlutterImageCompress.compressWithList(bytes, quality: quality);

    String bs64 = base64Encode(compressBytes);
    String bs64Image = "data:image/png;base64,$bs64";
    final res = await CommonRepository.uploadImgIdl(imgData: bs64Image);

    EasyLoading.dismiss();
    if (res.isNotEmpty) {
      EasyLoading.showSuccess('上传成功');
      setState(() {
        _imgUrls.add(res);
        if (widget.onChange != null) {
          widget.onChange!(_imgUrls);
        }
      });
    }
  }

  Widget _buildGridViewList() {
    return SizedBox(
      width: double.maxFinite,
      child: Wrap(
        spacing: 16.rpx,
        runSpacing: 16.rpx,
        children: [
          ..._imgUrls.map((item) => _builderImgItem(item)).toList(),
          if (!widget.isOnlyPreview &&
              (widget.maxCount == -1 || _imgUrls.length < widget.maxCount))
            _builderUploader()
        ],
      ),
    );
  }

  Widget _builderImgItem(String url) {
    return Container(
      width: widget.width ?? 150.rpx,
      height: widget.width ?? 150.rpx,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.black.withOpacity(0.1), width: 1.rpx),
      ),
      child: Stack(
        children: [
          GestureDetector(
            onTap: () {
              Navigator.of(context).push(
                FadeRoute(
                  page: GalleryPhotoViewPage(
                    galleryItems: _imgUrls.asMap().entries.map((e) {
                      GalleryExampleItem item = GalleryExampleItem();
                      item.id = 'tag+${e.key}';
                      item.resource = e.value;
                      return item;
                    }).toList(),
                    initialIndex: _imgUrls.indexOf(url),
                  ),
                ),
              );
            },
            child: CachedNetworkImage(
              imageUrl: url,
              fit: BoxFit.cover,
              width: widget.width ?? 160.rpx,
              height: widget.width ?? 160.rpx,
            ),
          ),
          if (!widget.isOnlyPreview)
            Positioned(
              top: 0,
              right: 0,
              child: IconButton(
                padding: EdgeInsets.zero,
                alignment: Alignment.topRight,
                onPressed: () {
                  showAlertDialog(
                    context: context,
                    content: const Text("确定要删除这张图片吗？"),
                    onCancel: () {
                      Navigator.of(context).pop();
                    },
                    onConfirm: () {
                      _deletePic(url);
                      Navigator.of(context).pop();
                    },
                  );
                },
                iconSize: 34.rpx,
                icon: Container(
                  color: Colors.black.withOpacity(0.6),
                  child: Icon(
                    Icons.close,
                    size: 34.rpx,
                    color: Colors.white,
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _builderUploader() {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());

        if(widget.onTap!= null) widget.onTap!();
        if (widget.maxCount > 0 && _imgUrls.length >= widget.maxCount) {
          EasyLoading.showInfo('最多可上传${widget.maxCount}张图片');
        } else {
          showCupertinoModalPopup(
            context: context,
            builder: (BuildContext context) => actionSheet(context),
          ).then((value) {});
        }
      },
      child: Container(
        width: widget.width ?? 160.rpx,
        height: widget.width ?? 160.rpx,
        color: widget.buttonColor,
        child: Center(
          child: Icon(
            Icons.add,
            size: 32,
            color: Colors.black.withOpacity(0.4),
          ),
        ),
      ),
    );
  }

  void _deletePic(String url) {
    setState(() {
      _imgUrls.remove(url);
      if (widget.onChange != null) {
        widget.onChange!(_imgUrls);
      }
    });
  }
}
